"""
    Discont module. Discribe disconts and associated classes.
"""

from datetime import date
from sqlobject import DatabaseIndex
from sqlobject.col import UnicodeCol, ForeignKey, IntCol, BoolCol, DateCol
from mnemoply.model.model_object import ModelObject
from mnemoply.model.columns import DecimalCol
from mnemoply.model.hub import __connection__
from mnemoply.utils import format_currency
from mnemoply.model import constants


class Discont(ModelObject): #TODO: fix mistake
    """
        Discont. May be persent or has rubles value.
    """

    model_title = _("Discont")

    name      = UnicodeCol(length=80, notNull=True, title=_("Name"))
    amount    = DecimalCol(default=None, size=10, precision=0, title=_("Discont in rubles"))
    percent   = IntCol(default=None, title=_("Discont in percent"))
    isActive  = BoolCol(default=False, title=_("Is active?"))
    isPercent = BoolCol(default=False, title=_("Is percent?"))
    comment   = UnicodeCol(default='', notNull=True, title=_("Comment"))
    year = IntCol(notNull=True, title=_("Year"), default=constants.getAcademicYear()+1)

    def getTitle(self):
        result = self.name
        if self.isPercent and self.percent:
            result += " (%d%%)" % self.percent
        elif self.amount:
            result += _(" (%s rub.)") % format_currency(self.amount)
        return result

    title = property(lambda self: self.getTitle())

class DiscontCard(ModelObject):
    """
        Dicsont card, one per student.
    """

    model_title = _("Discont card")

    student       = ForeignKey('Student', notNull=True, title=_("Student"))
    number        = UnicodeCol(length=80, default='', notNull=True, title=_("Number"))
    comment       = UnicodeCol(default='', notNull=True, title=_("Comment"))
    uniqueStudent = DatabaseIndex('studentID', unique=True)
    uniqueNumber  = DatabaseIndex('number', unique=True)

    title = property(lambda self: "%s (%s %s)" %
                     (self.number, self.student.surname, self.student.forename))

class PartnerType(ModelObject):
    """
        Partner type dictionary. Contains values `default`, `student`, `personal`.
    """

    model_title = _("Partner type")
    name = UnicodeCol(length=80, notNull=True, title=_("Name"))
    title = property(lambda self: self.name)

class Partner(ModelObject):
    """
        A man (student, teacher or someone else) who has a secret word
        and says this password to another student.
        Student with this password has a small discont on first payment.
    """

    model_title = _("Partner")

    surname    = UnicodeCol(length=80, default='', notNull=True, title=_("Surname"))
    forename   = UnicodeCol(length=80, default='', notNull=True, title=_("Forename"))
    patronymic = UnicodeCol(length=80, default='', notNull=True, title=_("Patronymic"))
    phone      = UnicodeCol(length=100, default='', notNull=True, title=_("Phone"))
    email      = UnicodeCol(length=140, default='', notNull=True, title=_("E-mail"))
    password   = UnicodeCol(length=200, default='', notNull=True, title=_("Partner password"))
    office     = ForeignKey('Office', default=None, title=_("Office"))
    comment    = UnicodeCol(default='', notNull=True, title=_("Comment"))
    partnerType = ForeignKey('PartnerType', notNull=True, title=_("Partner type"))
    creationDate = DateCol(notNull=True, default=date.today(), title=_("Creation date"))
    amountOfLeaflets = IntCol(default=None, title=_("Amount of leaflets"))

    title = property(lambda self: "%s (%s %s %s)" %
                     (self.password, self.surname, self.forename, self.patronymic))

    @classmethod
    def createNewPassword(cls, office=None):
        max_id = 1
        if cls.select().count():
            max_id = cls.select().max(cls.q.id) + 1
        str_next_id = "%d" % max_id
        if office is not None:
            return office.abbreviation + str_next_id
        return str_next_id

class FirstDiscont(ModelObject):
    """
        Additional information for first charge record creation.
        Also content information about how this agreement takes this discont.
    """

    model_title = _("First discont")

    agreement    = ForeignKey('StudentAgreement', notNull=True, title=_("Student agreement"))
    discont      = ForeignKey('Discont', default=None, title=_("Discont"))
    card         = ForeignKey('DiscontCard', default=None, title=_("Discont card"))
    partner      = ForeignKey('Partner', default=None, title=_("Partner"))
    isAlreadyUse = BoolCol(notNull=True, default=False, title=_("Is already use"))
    comment      = UnicodeCol(default='', notNull=True, title=_("Comment"))

    uniqueAgreement = DatabaseIndex('agreementID', unique=True)

    title = property(lambda self: self.agreement.title)
